package services

import (
	"errors"
	"gomvc/app/models"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

var Login = new(loginService)

type loginService struct {
	db *gorm.DB
}

func (e *loginService) UserLogin(username, password string, ctx *gin.Context) (string, error) {
	var user models.SysUser
	result := e.db.Where("Username=?", username).First(&user)
	// 执行是否成功
	if result.Error != nil {
		return "", result.Error
	}
	// 查询记录是否存在
	if result.RowsAffected == 0 {
		return "", errors.New("用户名或者密码不正确")
	}
	// 密码校验
	if password != user.Password {
		return "", errors.New("密码不正确")
	}
	// 状态验证先省了
	// 更新登录时间
	update := e.db.Model(&user).Where("UserId = ?", &user.UserId).Update("UpdatedAt", time.Now().Unix())
	if update.Error != nil {
		return "", update.Error
	}
	return "token", nil
}
